package dnl.net.netclip;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;

import javax.imageio.ImageIO;

/**
 * 
 * 
 * @author <a href="mailto:daniel.or@gmail.com">Daniel Or</a>
 * 
 */
public class ImageContent implements Serializable {

	private byte[] bytes;
	private String format;
	private static final String DEFAULT_FORMAT = "png";

	public ImageContent(byte[] bytes, String format) {
		this.bytes = bytes;
		this.format = format;
	}

	public byte[] getBytes() {
		return bytes;
	}

	public String getFormat() {
		return format;
	}

	public static ImageContent fromImage(Image image) throws IOException {
		return new ImageContent(grabImageBytes(image, DEFAULT_FORMAT), DEFAULT_FORMAT);
	}

	private static byte[] grabImageBytes(Image ima, String format) throws IOException {
		BufferedImage bu = new BufferedImage(ima.getWidth(null), ima
				.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics g = bu.getGraphics();
		g.drawImage(ima, 0, 0, null);
		g.dispose();

		ByteArrayOutputStream bas = new ByteArrayOutputStream();
		ImageIO.write(bu, "png", bas);
		byte[] data = bas.toByteArray();
		return data;
	}
}
